/*
 * SpeedoDyno - Speedometer and dynamometer application for Android 
 * Copyright 2013 Guilhem VALENTIN
 * 
 * This file is part of SpeedoDyno
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with SpeedoDyno. If not, see <http://www.gnu.org/licenses/>.
 */
package com.gvalentin.speedodyno.data;

import java.util.ListIterator;

import android.location.Location;

import com.gvalentin.speedodyno.util.DistanceElevation;
import com.gvalentin.speedodyno.util.DistanceRollingList;
import com.gvalentin.speedodyno.util.DoubleCapacityRollingList;

/**
 * Calculate incline by using average value.
 * - automatically remove nonsense GPS altitude values
 * - calculate average by compiling a minimum set of altitudes changes (so if altitude
 * does not change a lot, the average will be calculated against a longer travel distance)
 * - apply maximum change rate to avoid having values changing too fast
 * @author guilhem
 */
public class CalculatorInclineAdaptative implements Calculator<Double> {

	// Total distance to store (in meters)
	private final static double TOTAL_DISTANCE = 500.0d;

	// Threshold for removing nonsense values
	private final static double INCLINE_THRESHOLD = 0.4d; // grades over 40% are ignored

	// Minimum elevation changes (in meters) used to calculate incline
	private final static double MIN_ELEVATION = 10.0d;

	// The incline will change of only this fraction of difference to the new incline
	private final static double CHANGE_RATE = 0.2d;
	
	
	// previous elevation values
	private DistanceRollingList elevations = new DistanceRollingList(TOTAL_DISTANCE);
	
	// accuracy values
	private DoubleCapacityRollingList accuracies = new DoubleCapacityRollingList(100);
	
	// current incline
	private double incline = 0.0d;
	
	// previous incline
	private double previousIncline = 0.0d;
	
	
	/**
	 * Add new distance and elevation values to history
	 */
	private void add(DistanceElevation de) {
		// Do not add nonsense values
		if (Math.abs(de.elevation / de.distance) < INCLINE_THRESHOLD) {
			// Add new value in history
			elevations.add(de);
		}
	}
	
	/**
	 * Calculate the incline
	 * @see com.gvalentin.speedodyno.data.Calculator#calculate(android.location.Location, android.location.Location)
	 */
	@Override
	public void update(Location previous, Location current) {
		// Monitor location GPS accuracy
		if (current != null) {
			accuracies.add((double) current.getAccuracy());
			
			// When we have enough accuracy values...
			if (accuracies.size() > 4) {
				// Only consider altitude if accuracy is sufficient
				// We consider that accuracy is sufficient if it is less than the average accuracy
				// Doing this, we avoid less accurate values and focus only on most accurate ones.
				if (current.getAccuracy() > accuracies.getAverage()) {
					return;
				}
			}
		}
		
		// Add new location data to history
		if (previous != null && current != null) {
			double distance = current.distanceTo(previous);
			double elevation = current.getAltitude() - previous.getAltitude();
			if (distance != 0.0d) {
				add(new DistanceElevation(distance, elevation));
			}
		}
		
		// If history is not empty, we can calculate incline
		if (!elevations.isEmpty()) {
			double absElevation = 0.0d;
			double totalElevation = 0.0d;
			double totalDistance = 0.0d;
			ListIterator<DistanceElevation> iter = elevations.listIterator();
			// first reach the end of list to be able to iterate backward
		    while (iter.hasNext()) {
		        iter.next();
		    }
		    // iterate backward to get as many values as needed to reach the minimum elevations changes
			while (iter.hasPrevious() && absElevation < MIN_ELEVATION) {
				DistanceElevation de = iter.previous();
				absElevation += Math.abs(de.elevation);
				totalElevation += de.elevation;
				totalDistance += de.distance;
			}
			// If total distance is not null, we can calculate incline
			if (totalDistance != 0.0d) {
				incline = (totalElevation / totalDistance);
				double difference = incline - previousIncline;
				incline = previousIncline + (CHANGE_RATE * difference);
				
				previousIncline = incline;
			}
		}
	}
	
	@Override
	public Double getData() {
		return incline;
	}
}
